﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class StorageFeeLongInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public StorageFeeLongInterfaceBusiness()
        {
            this.InterfaceName = "FBA长期仓储费";
            //获取字段的映射关系
            tableField = GetMapField("addRow");
            //索引字段
            Keys = GetKeys("addRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置
                
                //获取源数据

                LX_StorageFeeLongInterfaceBusiness LX_StorageFeeLong = new LX_StorageFeeLongInterfaceBusiness();
                List<object> sourceData_t = await LX_StorageFeeLong.QueryAsync<object>(LX_StorageFeeLong.LX_Query, SqlDb);
                List<StorageFeeLong> sourceData = new List<StorageFeeLong>();
                //获取汇率
                List<LX_Rate.Data> rateList = SqlDb.GetListBySql<LX_Rate.Data>(@$"SELECT * FROM  SD_LX_Rate(NOLOCK) WHERE date >='{DateTime.Now.AddMonths(-3).ToString("yyyy-MM") + "-01"}' ");


                foreach (JObject item in sourceData_t)
                {
                    StorageFeeLong storageFeeLong = new StorageFeeLong();
                    storageFeeLong.sid = item["sid"].ToString();
                    storageFeeLong.snapshot_date = item["snapshot_date"].ToString();
                    storageFeeLong.sku = item["sku"].ToString();
                    storageFeeLong.fnsku = item["fnsku"].ToString();
                    storageFeeLong.asin = item["asin"].ToString();
                    storageFeeLong.product_name = item["product_name"].ToString();
                    storageFeeLong.condition = item["condition"].ToString();
                    storageFeeLong.qty_charged_12_mo_long_term_storage_fee = item["qty_charged_12_mo_long_term_storage_fee"].ToString();
                    storageFeeLong.per_unit_volume = item["per_unit_volume"].ToString();
                    storageFeeLong.currency = item["currency"].ToString();
                    storageFeeLong.s_12_mo_long_terms_storage_fee = item["12_mo_long_terms_storage_fee"].ToString();
                    storageFeeLong.qty_charged_6_mo_long_term_storage_fee = item["qty_charged_6_mo_long_term_storage_fee"].ToString();
                    storageFeeLong.s_6_mo_long_terms_storage_fee = item["6_mo_long_terms_storage_fee"].ToString();
                    storageFeeLong.volume_unit = item["volume_unit"].ToString();
                    storageFeeLong.country = item["country"].ToString();
                    storageFeeLong.is_small_and_light = item["is_small_and_light"].ToString();
                    storageFeeLong.enrolled_in_small_and_light = item["enrolled_in_small_and_light"].ToString();


                    //将币别转换成美元
                    if (storageFeeLong.currency.ToLower() != "usd")
                    {
                        var usd = rateList.Where(x => x.date.ToDateTime().ToString("yyyy-MM") == storageFeeLong.snapshot_date.ToDateTime().ToString("yyyy-MM") && x.code.ToLower() == "usd");
                        var currency = rateList.Where(x => x.date.ToDateTime().ToString("yyyy-MM") == storageFeeLong.snapshot_date.ToDateTime().ToString("yyyy-MM") && x.code.ToLower() == storageFeeLong.currency.ToLower());
                        if (!usd.IsNullOrEmpty() && !currency.IsNullOrEmpty())
                        {
                            var rate = currency.First().rate_org.ToDouble();
                            var rate_usd = usd.First().rate_org.ToDouble();
                            var cost1 = (storageFeeLong.s_6_mo_long_terms_storage_fee.ToDouble() * rate / rate_usd);
                            var cost2 = (storageFeeLong.s_12_mo_long_terms_storage_fee.ToDouble() * rate / rate_usd);
                            storageFeeLong.mo_long_terms_storage_fee = (cost1 + cost2).ToString("F6");
                        }

                    }
                    else
                    {
                        storageFeeLong.mo_long_terms_storage_fee = (storageFeeLong.s_6_mo_long_terms_storage_fee.ToDouble() + storageFeeLong.s_12_mo_long_terms_storage_fee.ToDouble()).ToString();
                    }
                    //storageFeeLong.qty_term_storage_fee = (storageFeeLong.qty_term_storage_fee.ToDouble() + storageFeeLong.qty_term_storage_fee.ToDouble()).ToString();
                    storageFeeLong.ID = storageFeeLong.sid + storageFeeLong.snapshot_date.ToDateTime().ToString("yyyy-MM-dd") + storageFeeLong.sku;
                    sourceData.Add(storageFeeLong);

                }
                //拼接生成ID
                //sourceData.ForEach(r => r.ID = r.sid + r.fulfillment_center + r.fnsku + r.average_quantity_on_hand + r.currency + r.country_code + r.month_of_charge + r.estimated_monthly_storage_fee);
                //过滤重复项
                //sourceData = sourceData.GroupBy(x => x.ID).Select(g => g.FirstOrDefault()).ToList();

                sourceData.GroupBy(x => x.ID).ForEach(x =>
                {
                    if (x.Count() > 1)
                    {
                        int c = 0;
                        x.ForEach(r =>
                        {
                            c++;
                            r.ID = r.ID + "-" + c;
                        });

                    }

                });
                //重复的行
                var G = sourceData.GroupBy(x => x.ID).Where(g => g.Count() > 1).ToList();
                //将重复的id编号变成唯一的id
                var date = sourceData.OrderBy(x => x.snapshot_date.ToDateTime()).ToList();
                //获取目标数据
                List<StorageFeeLong> targetData = new List<StorageFeeLong>();//目标据集合
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "66d981341214257ad192931d", DataType = 15, SpliceType = 1, FilterType = 14, Value = date[0].snapshot_date.ToDateTime().ToString("yyyy-MM-dd") }//FDATE字段过滤日开始700天前到现在的数据
            );
                targetData = await QueryAsync<StorageFeeLong>(queryOption, tableField, SqlDb);


                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<StorageFeeLong> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<StorageFeeLong>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<StorageFeeLong> insertItem = sourceData.Except(targetData, new ComparerFromKey<StorageFeeLong>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<StorageFeeLong> deleteItem = targetData.Except(sourceData, new ComparerFromKey<StorageFeeLong>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<StorageFeeLong> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion

                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                    sqlDBInterface.ExecuteInterface<StorageFeeLong>(sourceData, "SD_LX_StorageFeeLong", $" WHERE  snapshot_date >= '{date[0].snapshot_date.ToDateTime().ToString("yyyy-MM-dd")}'");
                }
                else
                {

                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
